package com.wy.Service.impl;

import com.wy.Service.BaseService;
import com.wy.vo.PageVo;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

@Service("baseService")
@Transactional    //事务注解具有继承性
public class BaseServiceImpl implements BaseService {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public PageVo searchPagination(Integer current, Integer pageSize, String hql, Object dto) {
        Session session = entityManager.unwrap(Session.class);
        //创建hql语句，设置多条件分页信息
        Query query = session.createQuery(hql);
        query.setProperties(dto).setFirstResult((current-1)*pageSize).setMaxResults(pageSize);
        //执行查询操作
        List rows = query.list();
        Integer index = hql.indexOf("from");
        String countHql = "select count(1)"+hql.substring(index).replace("fetch","");
        Object total = session.createQuery(countHql).setProperties(dto).uniqueResult();
        PageVo pageVo = new PageVo();
        pageVo.setRows(rows);
        pageVo.setTotal(Long.parseLong(total.toString()));
        return pageVo;
    }
}